/*
* 退货管理
* */

import 'package:center_beijing/api/component_api.dart';
import 'package:center_beijing/api/factory_api.dart';
import 'package:center_beijing/common/QRScan.dart';
import 'package:center_beijing/common/custom_floatingAction_buttonLocation.dart';
import 'package:center_beijing/common/notification.dart';
import 'package:center_beijing/common/styles.dart';
import 'package:center_beijing/config/global_config.dart';
import 'package:center_beijing/config/routeConfig.dart';
import 'package:center_beijing/models/selectItem.dart';
import 'package:center_beijing/widgets/custom_loading_widget.dart';
import 'package:center_beijing/widgets/custom_select_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';

class ReturnProduction extends StatefulWidget {
  @override
  _ReturnProductionState createState() => _ReturnProductionState();
}

class _ReturnProductionState extends State<ReturnProduction> {
  CustomLoading loading = CustomLoading.withMessage('请稍候...');
  EasyRefreshController _controller = EasyRefreshController();
  List<SelectItems> projectNameList = [
    SelectItems(
      label: '全部',
      value: '',
    )
  ];
  SelectItems selectProject = SelectItems(
    label: '全部',
    value: '',
  );
  List dataSource = [];
  int page = 1;
  int pageSize = 15;

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    loading.dismiss();
  }
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    bus.on('refreshReturn', (arg) {
      page = 1;
      this.getOrders();
    });
    this.getOrders();
    this.getComp();
  }

  /*
  * 获取运输单
  * */
  getOrders() async {
    var pass = {'projectId': GlobalConfig.selectFactory.value};
    var result = await getAllOrders(pass);
    if (result != null) {
      result.forEach((item) {
        projectNameList.add(SelectItems(
            label: item['sendNumber'], value: item['id'], dict: item));
      });
    }
  }

  /*
  * 获取可退货构件
  * */
  getComp() async {
    var pass = {
      'projectId': GlobalConfig.selectFactory.value,
      'transportId': selectProject.value,
      'page': this.page,
      'page-size': 15,
      'isReturn': 1
    };
    var result = await getReturnComp(pass);
    if (result != null) {
      if (this.page == 1) {
        dataSource.clear();
      }
      if (result != null) {
        if (result['data'].length == 0) {
        } else {
          dataSource.addAll(result['data']);
        }
      }
      this.setState(() {});
    }
  }

  /*
  * 获取构件详情
  * */
  getCompDetail(compId) async {
    loading.show(delay: 15);
    var result = await getComponentDetail(compId);
    loading.dismiss();
    if (result != null) {
      Get.toNamed(
          RouteConfig.addReturnProjection,
          arguments: result);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('退货管理'),
      ),
      body: SafeArea(
        child: Container(
          child: Column(
            children: [
              Container(
                color: Colors.white,
                margin: EdgeInsets.fromLTRB(0, 0, 0, 0),
                child: CustomSelectWidget(
                  require: true,
                  rightText:
                      selectProject.label != null ? selectProject.label : '请选择',
                  items: projectNameList,
                  selectCallback: (value) {
                    this.setState(() {
                      selectProject = value;
                      this.getComp();
                    });
                  },
                  title: '运输单号',
                ),
              ),
              Expanded(
                  child: this.dataSource.length > 0
                      ? EasyRefresh.custom(
                      shrinkWrap: true,
                      firstRefresh: false,
                      controller: _controller,
                      header: MaterialHeader(),
                      footer: ClassicalFooter(
                          loadingText: '加载中',
                          loadText: '上拉加载',
                          noMoreText: '没有更多数据',
                          loadedText: '加载完成',
                          infoText: '更新于 %T',
                          textColor: Styles.NoMoreColor,
                          showInfo: false),
                      emptyWidget: (dataSource.length == 0)
                          ? Center(
                        child: Image(
                          image:
                          AssetImage('assets/images/no_data.png'),
                          width: 128,
                          height: 150,
                        ),
                      )
                          : null,
                      onRefresh: () async {
                        // _controller.finishLoad(success: true, noMore: false);
                        if (mounted) {
                          page = 1;
                          this.getComp();
                        }
                      },
                      onLoad: () async {
                        await Future.delayed(Duration(seconds: 2), () {
                          if (mounted) {
                            page++;
                            this.getComp();
                          }
                        });
                      },
                      slivers: <Widget>[
                        SliverList(
                          delegate: SliverChildBuilderDelegate(
                                (context, index) {
                              return GestureDetector(
                                onTap: () {
                                  Get.toNamed(
                                      RouteConfig.addReturnProjection,
                                      arguments: this.dataSource[index]['orderCompInfo']);
                                },
                                child: Container(
                                  color: Colors.white,
                                  padding: EdgeInsets.fromLTRB(
                                      Styles.spacing16,
                                      Styles.spacing8,
                                      Styles.spacing16,
                                      Styles.spacing8),
                                  margin: EdgeInsets.fromLTRB(
                                      Styles.spacing8,
                                      Styles.spacing4,
                                      Styles.spacing8,
                                      Styles.spacing4),
                                  child: Column(
                                    crossAxisAlignment:
                                    CrossAxisAlignment.start,
                                    children: [
                                      Row(
                                        children: [
                                          Container(
                                            margin: EdgeInsets.only(
                                                right: Styles.spacing8),
                                            height: 20.h,
                                            width: 4.w,
                                            color: Styles.BlueColor,
                                          ),
                                          Container(
                                            padding: EdgeInsets.fromLTRB(
                                                0,
                                                Styles.spacing8,
                                                0,
                                                Styles.spacing8),
                                            child: Text(
                                                "${this.dataSource[index]['transportForm']['orderName']}"),
                                          ),
                                        ],
                                      ),
                                      Container(
                                        padding: EdgeInsets.fromLTRB(
                                            0,
                                            Styles.spacing8,
                                            0,
                                            Styles.spacing8),
                                        child: Text(
                                            "运输车辆 ${this.dataSource[index]['transportForm']['transportCar']['vehicleNum']}"),
                                      ),
                                      Container(
                                        padding: EdgeInsets.fromLTRB(
                                            0,
                                            Styles.spacing8,
                                            0,
                                            Styles.spacing8),
                                        child: Text(
                                            "运输人 ${this.dataSource[index]['transportForm']['transportCar']['transportPerson']}"),
                                      ),
                                      Container(
                                        padding: EdgeInsets.fromLTRB(
                                            0,
                                            Styles.spacing8,
                                            0,
                                            Styles.spacing8),
                                        child: Text(
                                            "运输单号 ${this.dataSource[index]['transportForm']['sendNumber']}"),
                                      ),
                                      Container(
                                        padding: EdgeInsets.fromLTRB(
                                            0,
                                            Styles.spacing8,
                                            0,
                                            Styles.spacing8),
                                        child: Text(
                                            "构件类型 ${this.dataSource[index]['orderCompInfo']['compKind']['compKindName']}"),
                                      ),
                                      Container(
                                        padding: EdgeInsets.fromLTRB(
                                            0,
                                            Styles.spacing8,
                                            0,
                                            Styles.spacing8),
                                        child: Text(
                                            "构件编号 ${this.dataSource[index]['orderCompInfo']['code']}"),
                                      )
                                    ],
                                  ),
                                ),
                              );
                            },
                            childCount: dataSource.length,
                          ),
                        ),
                      ])
                      : Container(
                    alignment: Alignment.center,
                    child: Image(
                      image: AssetImage('assets/images/no_data.png'),
                      width: 128,
                      height: 150,
                    ),
                  ),)
            ],
          ),
        ),
      ),
        floatingActionButtonLocation: CustomFloatingActionButtonLocation(
          FloatingActionButtonLocation.endFloat,
        ),
        floatingActionButtonAnimator: NoScalingAnimation(),
        floatingActionButton: FloatingActionButton(
            child: Image.asset(
              'assets/images/saoyisao.png',
              fit: BoxFit.fill,
            ),
            onPressed: () async {
              FocusScope.of(context).requestFocus(new FocusNode());
              var result = await QrScan.scan(context, type: 1);
              if (result != null) {
                if (result['type'] == 1) {
                  this.getCompDetail(result['code']);
                } else {
                  showDialog(
                      barrierDismissible: false,
                      context: context,
                      builder: (BuildContext context) {
                        return AlertDialog(
                          title: Text('注意'),
                          content: Text('请扫正确的二维码！'),
                          actions: <Widget>[
                            new Container(
                              child: FlatButton(
                                child: new Text(
                                  "确定",
                                  style: TextStyle(color: Colors.red),
                                ),
                                onPressed: () {
                                  Navigator.pop(context);
                                },
                              ),
                            ),
                          ],
                        );
                      });
                }
              }
            },
            backgroundColor: Colors.transparent)
    );
  }
}
